<template>
  <div class="login-container">
    <div class="login-form1">
      <header class="head-logo">
        <!-- <img src="../../assets/login/head.png" alt="" /> -->
        <div class="p1">欢迎登录</div>
        <div class="p2">保镖人才网管理中心</div>
      </header>
      <div class="login">
        <a-form ref="formRef" :model="form" :rules="rules" @keyup.enter="handleSubmit">
          <a-form-item name="username">
            <a-input v-model:value="form.username" autocomplete="off" placeholder="请输入账号" class="inp">
              <template v-slot:prefix>
                <UserOutlined style="color: rgba(0, 0, 0, 0.25)" />
              </template>
            </a-input>
          </a-form-item>
          <a-form-item name="password">
            <a-input-password v-model:value="form.password" autocomplete="off" placeholder="请输入密码" class="inp">
              <template v-slot:prefix>
                <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
              </template>
            </a-input-password>
          </a-form-item>

          <!-- <div>{{ yanshow ? `<div>1</div>`: `<div>2</div>`  }}</div> -->
          <a-form-item name="yan" v-if="yanshow" :rules="[
            {
              required: true,
              message: '请输入验证码',
              trigger: 'change',
            },
          ]">
            <a-input v-model:value="form.yan" autocomplete="off" placeholder="请输入验证码" class="inps">
              <template v-slot:prefix>
                <img @click="newimg()" class="imgyans" :src="imgurl" alt="" />
              </template>
            </a-input>
          </a-form-item>

          <div>
            <SliderCheck :successFun="handleSuccessFun" :errorFun="handleErrorFun"></SliderCheck>
          </div>
          <a-form-item>
            <button @click="handleSubmit()">
              <div class="svg-wrapper-1">
                <div class="svg-wrapper">
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
                    <path fill="none" d="M0 0h24v24H0z"></path>
                    <path fill="currentColor"
                      d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.455.547-.679.045L12 14l6-8-8 6-8.054-2.685z">
                    </path>
                  </svg>
                </div>
              </div>
              <span>登录</span>
            </button>
          </a-form-item>
        </a-form>

        <div v-if="yanshow">
          验证码： <span id="yancopy">{{ imgtext }}</span>
          <CopyOutlined id="yancopys" @click="textcopy()" style="color: rgba(0, 0, 0, 0.25)" />
        </div>
      </div>
    </div>

    <!-- 摄像头调用验证区域 -->
    <!-- <div class="mov">
      <Row :gutter="16">
        <Col span="12">
          <div class="camera_outer" style="position: relative">
            <video id="videoCamera" width="480" height="560" autoplay></video>
            <canvas
              style="display: block; position: absolute; top: 0"
              width="480"
              height="560"
              id="canvasCamera"
            ></canvas>
            <div class="button">
              <button @click="getCompetence()">打开摄像头</button>
              <button @click="stopNavigator()">关闭摄像头</button>
              <button @click="setImage()">拍照</button>
            </div>
          </div>
        </Col>
        <Col span="12">
          <div v-if="imgSrc" class="img_bg_camera">
            <p>效果预览</p>
            <img :src="imgSrc" alt class="tx_img" />
          </div>
        </Col>
      </Row>
    </div> -->
  </div>
</template>

<script lang="ts">
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";
import { LoginFrom } from "@/types/views/login";
import axios from "axios";

import {
  defineComponent,
  getCurrentInstance,
  onMounted,
  reactive,
  ref,
  UnwrapRef,
  onBeforeMount,
} from "vue";
import {
  UserOutlined,
  LockOutlined,
  CopyOutlined,
} from "@ant-design/icons-vue";
export default defineComponent({
  name: "login",
  components: {
    UserOutlined,
    LockOutlined,
    CopyOutlined,
  },

  setup() {
    // 表单数据
    const form = data_form();
    // 滑块验证码区域
    const SildingBlock = ref(false);
    const yanshow = ref(false);
    const handleSuccessFun = () => {
      SildingBlock.value = true;
    };
    const handleErrorFun = () => {
      // SildingBlock.value=true
      message.info("尚未验证，验证通过后可以登录");
    };
    const rules = reactive({
      username: [
        {
          required: true,
          message: "请输入账号",
          trigger: "change",
        },
      ],
      password: [
        {
          required: true,
          message: "请输入密码",
          trigger: "change",
        },
      ],
    });

    const formRef = ref();
    const imgurl = ref("");
    const imgtext = ref("");
    const number = ref(0);

    const store = useStore();

    const router = useRouter();

    /**
     * @desc: 登录提交
     * @param 无
     */


    const handleSubmit = (): void => {
      if (yanshow.value == false) {
        formRef.value.validate().then(() => {
          store
            .dispatch("user/login", form)
            .then((e) => {
              console.log(e);
              if (e.code == 200) {
                const route = router.currentRoute.value;
                const url = route.query.redirect || "/";
                router.push(url as string);
              } else {
                message.error(e.message || e.data.message);
                number.value += 1;
                console.log(number.value);
                if (number.value >= 3) {
                  yanshow.value = true;
                }
              }
            })
            .catch((err) => {});
        });
      }else{
        if (form.yan.toLowerCase() == imgtext.value.toLowerCase()) {
          formRef.value.validate().then(() => {
          store
            .dispatch("user/login", form)
            .then((e) => {
              console.log(e);
              if (e.code == 200) {
                const route = router.currentRoute.value;
                const url = route.query.redirect || "/";
                router.push(url as string);
              } else {
                message.error(e.message || e.data.message);
              }
            })
            .catch((err) => {});
        });
        }else{
          message.error('验证码错误！')
        }
      }
    };

    const textcopy = () => {
      var input = document.getElementById("yancopy");
      let oInput = document.createElement("input");
      oInput.value = input?.innerText;
      document.body.appendChild(oInput);
      oInput.select(); // 选择对象;
      document.execCommand("Copy"); // 执行浏览器复制命令
      oInput.remove();
      message.success(oInput.value + "复制成功！");
    };

    const newimg = () => {
      getyan();
    };

    // const getCompetence=()=> {
    //   var _this = this;
    //   var a = document.getElementById("canvasCamera");
    //   var b = a.getContext("2d");
    //   this.thisVideo = document.getElementById("videoCamera");
    //   this.thisVideo.style.display = 'block';

    //   var tracker = new tracking.ObjectTracker('face');
    //   tracker.setInitialScale(4);
    //   tracker.setStepSize(2);
    //   tracker.setEdgesDensity(0.1);

    //     this.trackerTask = tracking.track('#videoCamera', tracker, { camera: true });

    //     tracker.on('track', function(event) {
    //       b.clearRect(0, 0, a.width, a.height);

    //       event.data.forEach(function(rect){
    //         b.font = '18px Helvetica';
    //         b.fillText("已识别到人脸，请静止等待拍照",100,40);
    //         b.strokeStyle = 'lawngreen';
    //         b.strokeRect(rect.x, rect.y, rect.width, rect.height);
    //         // setTimeout(_this.setImage(),60000);
    //       });
    //     });
    //   // 获取媒体属性，旧版本浏览器可能不支持mediaDevices，我们首先设置一个空对象
    //   if (navigator.mediaDevices === undefined) {
    //     navigator.mediaDevices = {};
    //   }
    //   // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
    //   // 使用getUserMedia，因为它会覆盖现有的属性。
    //   // 这里，如果缺少getUserMedia属性，就添加它。
    //   if (navigator.mediaDevices.getUserMedia === undefined) {
    //     navigator.mediaDevices.getUserMedia = function(constraints) {
    //       // 首先获取现存的getUserMedia(如果存在)
    //       var getUserMedia =
    //         navigator.webkitGetUserMedia ||
    //         navigator.mozGetUserMedia ||
    //         navigator.getUserMedia;
    //       // 有些浏览器不支持，会返回错误信息
    //       // 保持接口一致
    //       if (!getUserMedia) {//不存在则报错
    //         return Promise.reject(
    //           new Error("getUserMedia is not implemented in this browser")
    //         );
    //       }
    //       // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
    //       return new Promise(function(resolve, reject) {
    //         getUserMedia.call(navigator, constraints, resolve, reject);
    //       });
    //     };
    //   }
    //   var constraints = {
    //     audio: false,
    //     video: {
    //       width: this.videoWidth,
    //       height: this.videoHeight,
    //       transform: "scaleX(-1)"
    //     }
    //   };
    //   navigator.mediaDevices
    //     .getUserMedia(constraints)
    //     .then(function(stream) {
    //       // 旧的浏览器可能没有srcObject
    //       if ("srcObject" in _this.thisVideo) {
    //         _this.thisVideo.srcObject = stream;
    //       } else {
    //         // 避免在新的浏览器中使用它，因为它正在被弃用。
    //         _this.thisVideo.src = window.URL.createObjectURL(stream);
    //       }
    //       _this.thisVideo.onloadedmetadata = function(e) {
    //         _this.thisVideo.play();
    //       };
    //     })
    //     .catch(err => {
    //       console.log(err);
    //     });
    // };
    //  绘制图片（拍照功能）
    // const setImage=()=> {
    //     var _this = this;
    //     // canvas画图
    //     var a = document.getElementById("canvasCamera");
    //     var b = a.getContext("2d");
    //     b.drawImage(
    //       _this.thisVideo,
    //       0,
    //       0,
    //       _this.videoWidth,
    //       _this.videoHeight
    //     );
    //     // 获取图片base64链接
    //     var image = a.toDataURL("image/png");
    //     _this.imgSrc = image;//赋值并预览图片
    //     _this.stopNavigator();
    //     return;
    //   };
    // 关闭摄像头
    // const stopNavigator=()=> {
    //   this.thisVideo.srcObject.getTracks()[0].stop();
    // }

    const getyan = async () => {
      // console.log("验证码");
      const { data } = await axios.get(
        // "https://api.a20safe.com/api.php?api=25&key=a352022750a981cddabc4ddd6e68231b&num=6&char=0&type=2&lev=2"
        "http://api.a20safe.com/api.php?api=25&key=69ec1bc7ee309e2e9442cb020378d74d&num=6&char=0&type=2&lev=2."
      );
      // console.log(data);
      imgurl.value = data.data[0].url;
      imgtext.value = data.data[0].text;
    };

    onMounted(() => {
      // dom 挂载前
      getyan();
    });

    return {
      // setImage,
      // stopNavigator,
      // getCompetence,
      formRef,
      form,
      yanshow,
      textcopy,
      rules,
      imgurl,
      imgtext,
      number,
      newimg,
      handleSubmit,
      SildingBlock,
      handleSuccessFun,
      handleErrorFun,
    };
  },
});

function data_form() {
  const form: UnwrapRef<LoginFrom> = reactive({
    username: undefined,
    password: undefined,
    yan: undefined,
  });
  return form;
}
</script>

<style lang="scss" scoped>
.login-container {
  width: 100vw;
  height: 100vh;
  background: url("@/assets/login/login_back.png") 100%;
  background-size: cover;

  .login-form1 {
    width: 500px;
    // background: rgba($color: #FAFAFA, $alpha:   .2);
    background: white;
    // height: 450px;
    border-radius: 10px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    // background: url('/src/assets/login/form_bg.png') no-repeat 100%/cover;
    box-shadow: 1px 2px 3px rgba($color: #fafafa, $alpha: 0.5);
    padding: 0px 10px;

    .head-logo {
      width: 100%;
      // overflow: hidden;
      position: relative;

      .p1 {
        position: absolute;
        // text-align: center;
        font-size: 24px;
        left: 50%;
        // top: 100%;
        transform: translate(-50%, 60%);
        // margin-top: 30px;
      }

      .p2 {
        position: absolute;
        font-size: 14px;
        left: 50%;
        color: #999;
        transform: translate(-50%, 260%);
      }
    }

    .login {
      width: 100%;
      margin-top: 100px;
      padding: 0 50px;

      .btn {
        margin-top: 20px;
        width: 100%;
        height: 45px;
        border-radius: 7px;
        // line-height: 40px;
      }

      button {
        text-align: center;
        width: 100%;
        font-family: inherit;
        font-size: 20px;
        background: rgb(64, 158, 255);
        color: white;
        padding: 0.5em 1em;
        padding-left: 7.5em;
        display: flex;
        align-items: center;
        border: none;
        border-radius: 16px;
        overflow: hidden;
        transition: all 0.2s;
      }

      button span {
        display: block;
        margin-left: 0.3em;
        transition: all 0.3s ease-in-out;
      }

      button svg {
        // margin-left: 190px;
        display: block;
        transform-origin: center center;
        transition: transform 0.5s ease-in-out;
      }

      button:hover .svg-wrapper {
        animation: fly-1 0.6s ease-in-out infinite alternate;
      }

      button:hover svg {
        transform: translateX(1.2em) rotate(45deg) scale(1.1);
      }

      button:hover span {
        transform: translateX(13em);
      }

      button:active {
        transform: scale(0.95);
      }

      @keyframes fly-1 {
        from {
          transform: translateY(0.1em);
        }

        to {
          transform: translateY(-0.1em);
        }
      }

      .inp {
        padding: 15px;
      }

      .inps {
        padding: 15px 150px 15px 15px;
        position: relative;

        .imgyans {
          position: absolute;
          height: 100%;
          width: 39%;
          left: 61%;
          border-left: 0.1px solid #999;
        }
      }
    }
  }

  #yancopys {
    margin-left: 5px;
    cursor: pointer;
  }

  .mov {
    width: 600px;
    background: pink;
  }

  .show {}

  .unshow {
    display: none;
  }
}
</style>
<!-- <style lang="scss">
</style> -->